# -*- coding:utf-8 -*-
from flask import request, jsonify, abort
from flask_cors import CORS
from com.zzh.dao_v2.memberDao import MemberDaoYM
import time
from . import app
from com.zzh.dao_v2.AuthTokenOperation import authTokenOperation
import traceback
localTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))


CORS(app, supports_credentials=True)

"""
表名：zzh_member

说明：会员信息表（包含个人和单位）
"""

@app.route('/queryMemberById', methods=['POST'])
def queryMemberById():

    if not request.json:
        abort(400)
    id = request.json.get("id")
    total_count, userCodeJSON= MemberDaoYM().queryMemberById(id)
    if total_count:
        return jsonify({"message": {"code": 1, "status": "queryMember OK"},"info":userCodeJSON})
    else:
        return jsonify({"info": [], "message": {"code": 1, "status": "No data"}})




@app.route('/queryMemberByCondition', methods=['POST'])
def queryMemberByCondition():

    if not request.json:
        abort(400)
    try:
        page = request.json['page']
        pageIndex = page["pageIndex"]
        pageSize = page["pageSize"]
    except:
        return jsonify({"message": {"code": 0, "status": "请传入 pageIndex和pageSize"}})
    try:
        conditions = request.json['condition']
    except:
        return jsonify({"message": {"code": 0, "status": "未传入指定condition"}})
    try:
        multiSort = request.json['multiSort']
    except:
        return jsonify({"message": "未传入排序规则multiSort"})
    try:
        total_count, UserCodeJSON = MemberDaoYM().queryMemberByCondition(pageIndex=pageIndex, pageSize=pageSize,conditions=conditions, multiSort=multiSort)
        if total_count:
                return jsonify({"message": {"code": 1, "status": "queryMember OK"},"total":total_count,"info":UserCodeJSON})
        else:
            return jsonify({"info": [], "message": {"code": 1, "status": "No data"}})
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})



@app.route('/insertMember', methods=['POST'])
def insertMember():

    if not request.json:

        abort(400)

    Info = {

        'userId': request.json.get('userId'),  #
        'invited_code': request.json.get('invited_code'), #
        'member_code': request.json.get('member_code'),  #
        'member_name': request.json.get('member_name'),


        'member_email': request.json.get('member_email'),  #
        'member_points': request.json.get('member_points'), #
        'member_balance': request.json.get('member_balance'),  #
        'member_expired': request.json.get('member_expired'),
        'industry_id': request.json.get('industry_id'),


        'province_id': request.json.get('province_id'),  #
        'city_id': request.json.get('city_id'), #
        'district_id': request.json.get('district_id'),  #
        'member_favorite_count': request.json.get('member_favorite_count'),
        'member_address': request.json.get('member_address'),


        'member_busness': request.json.get('member_busness'),  #
        'member_type': request.json.get('member_type'), #
        'sp_knowledge': request.json.get('sp_knowledge'),  #
        'sp_revenue': request.json.get('sp_revenue'),
        'sp_employee': request.json.get('sp_employee'),


        'sp_industrycode': request.json.get('sp_industrycode'),  #
        'tm_industrycode': request.json.get('tm_industrycode'), #
        'tm_deptcode': request.json.get('tm_deptcode'),  #
        'tm_level': request.json.get('tm_level'),
        'register_code': request.json.get('register_code'),
        'is_vip': request.json.get('is_vpi')

    }



    if not Info:
        return jsonify({"message": {"code": 0, "info": "信息填写未完整"}})
    try:
        rs = MemberDaoYM().insertMember(Info)
        if rs:
            return jsonify(
                {"massage": {"code": 1, "info": "addMember OK"}})  # 添加函数调用成功，返回添加的信息（不包括userRecharge的Id）
        else:
            return jsonify({"message": {"code": 0, "info": "addMember Error"}})  # 添加函数调用失败
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})




@app.route('/updateMember', methods=['POST'])
def updateMember():#
        if not request.json:
            abort(400)


        try:
            id = request.json.get('id')
        except:
            return jsonify({"message": {"code": 0, "status": "请传入 id"}})
        try:
            oldInfo = MemberDaoYM().selectMember(id)
        except Exception, e:
            return jsonify({"message": {"code": 0, "info": str(e)}})
        Info = {

            'id': request.json.get('id'),  #
            'userId': request.json.get('userId', oldInfo[1]),  #
            'invited_code': request.json.get('invited_code', oldInfo[2]),  #
            'member_code': request.json.get('member_code', oldInfo[3]),  #
            'member_name': request.json.get('member_name', oldInfo[4]),

            'member_email': request.json.get('member_email', oldInfo[5]),  #
            'member_points': request.json.get('member_points', oldInfo[6]),  #
            'member_balance': request.json.get('member_balance', oldInfo[7]),  #
            'member_expired': request.json.get('member_expired', oldInfo[8]),
            'industry_id': request.json.get('industry_id', oldInfo[9]),

            'province_id': request.json.get('province_id', oldInfo[10]),  #
            'city_id': request.json.get('city_id', oldInfo[11]),  #
            'district_id': request.json.get('district_id', oldInfo[12]),  #
            'member_favorite_count': request.json.get('member_favorite_count', oldInfo[13]),
            'member_address': request.json.get('member_address', oldInfo[14]),

            'member_busness': request.json.get('member_busness', oldInfo[15]),  #
            'member_type': request.json.get('member_type', oldInfo[16]),  #
            'sp_knowledge': request.json.get('sp_knowledge', oldInfo[17]),  #
            'sp_revenue': request.json.get('sp_revenue', oldInfo[18]),
            'sp_employee': request.json.get('sp_employee', oldInfo[19]),

            'sp_industrycode': request.json.get('sp_industrycode', oldInfo[20]),  #
            'tm_industrycode': request.json.get('tm_industrycode', oldInfo[21]),  #
            'tm_deptcode': request.json.get('tm_deptcode', oldInfo[22]),  #
            'tm_level': request.json.get('tm_level', oldInfo[23]),
            'register_code': request.json.get('register_code', oldInfo[23]),
            'is_vip': request.json.get('is_vip', oldInfo[24])

        }
        if not Info:
            return jsonify({"message": {"code": 0, "info": "信息填写未完整"}})
        try:
            rs, memberInfo = MemberDaoYM().updateMember(Info)
            return jsonify({"info": memberInfo, "massage": {"code": 1, "info": "updateMember OK"}})  # 添加函数调用成功，返回添加的信息
        except Exception, e:
            return jsonify({"message": {"code": 0, "info": str(e)}})






@app.route('/updateMemberByUserId', methods=['POST'])
def updateMemberByUserId():#
        if not request.json:
            abort(400)


        try:
            userId = request.json.get('userId')
        except:
            return jsonify({"message": {"code": 0, "status": "请传入userId"}})
        try:
            oldInfo = MemberDaoYM().selectMemberByUserId(userId)


        except Exception, e:
            return jsonify({"message": {"code": 0, "info": str(e)}})
        Info = {

            'member_id': request.json.get('memeberId',oldInfo[0]),  #
            'user_id': request.json.get('userId', oldInfo[1]),  #
            'invited_code': request.json.get('invitedCode', oldInfo[2]),  #
            'member_code': request.json.get('memberCode', oldInfo[3]),  #
            'member_name': request.json.get('memberName', oldInfo[4]),

            'member_email': request.json.get('memberEmail', oldInfo[5]),  #
            'member_points': request.json.get('memberPoints', oldInfo[6]),  #
            'member_balance': request.json.get('memberBalance', oldInfo[7]),  #
            'member_expired': request.json.get('memberExpired', oldInfo[8]),
            'industry_id': request.json.get('industryId', oldInfo[9]),

            'province_id': request.json.get('provinceId', oldInfo[10]),  #
            'city_id': request.json.get('cityId', oldInfo[11]),  #
            'district_id': request.json.get('districtId', oldInfo[12]),  #
            'member_favorite_count': request.json.get('memberFavoriteCount', oldInfo[13]),
            'member_address': request.json.get('memberAddress', oldInfo[14]),

            'member_busness': request.json.get('memberBusness', oldInfo[15]),  #
            'member_type': request.json.get('memberType', oldInfo[16]),  #
            'sp_knowledge': request.json.get('spKnowledge', oldInfo[17]),  #
            'sp_revenue': request.json.get('spRevenue', oldInfo[18]),
            'sp_employee': request.json.get('spEmployee', oldInfo[19]),

            'sp_industrycode': request.json.get('spIndustrycode', oldInfo[20]),  #
            'tm_industrycode': request.json.get('tmIndustrycode', oldInfo[21]),  #
            'tm_deptcode': request.json.get('tmEeptcode', oldInfo[22]),  #
            'tm_level': request.json.get('tmLevel', oldInfo[23]),
            'register_code': request.json.get('registerCode', oldInfo[24]),
            'is_vip': request.json.get('isVip', oldInfo[25])
        }

        if not Info:
            return jsonify({"message": {"code": 0, "info": "信息填写未完整"}})
        try:
            rs = MemberDaoYM().updateMemberByUserId(Info)
            tc, newInfo = MemberDaoYM().queryMemberByUserId(userId)


            return jsonify({"Info":newInfo ,"message": {"code": 1, "info": "updateMember OK"}})  # 添加函数调用成功，返回添加的信息
        except Exception, e:
            return jsonify({"message": {"code": 0, "info": str(e)}})





@app.route('/deleteMember', methods=['POST'])  # 根据id数组删除zzh_user_Code表指定记录,传入格式为 "ids":[1,2,3,4]
def deleteMember():
    ids = request.json.get("ids")
    if not ids:
        return jsonify({"message":"请输入待删除的  id数组！"})
    try:
        rs = MemberDaoYM().deleteMember(ids)
        if rs:
            return jsonify({"message": {"code": 1, "info": "deleteMember OK"}})
        else:
            return jsonify({"message": {"code": 0, "info": "deleteMember Error"}})
    except Exception, e:
            return jsonify({"message": {"code": 0,  "info": str(e)}})


